package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.regexp.internal.RE;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author gsy
 * @date 2021年08月24日18:31
 * Description
 */
@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public List<BaseCategory1> getCategory1() {

        return baseCategory1Mapper.selectList(null);

    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {

        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {

        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));

    }

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    @Transactional
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() != null) {
            //修改平台属性
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //根据平台id查询删除对应的旧属性值
            baseAttrValueMapper.delete(new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId()));

        } else {
            //添加平台属性
            baseAttrInfoMapper.insert(baseAttrInfo);

        }
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //添加或修改平台属性值
        if (attrValueList != null && attrValueList.size() > 0) {
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //添加对应的属性值
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }


    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {

        QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();

        baseAttrValueQueryWrapper.eq("attr_id", attrId);

        return baseAttrValueMapper.selectList(baseAttrValueQueryWrapper);
    }

    @Override
    public IPage<BaseTrademark> baseTrademark(Integer page, Integer limit) {
        IPage<BaseTrademark> iPage = baseTrademarkMapper.selectPage(new Page<>(page, limit), null);
        return iPage;
    }

    @Override
    public void remove(Long trademarkId) {

        baseTrademarkMapper.deleteById(trademarkId);
    }

    @Override
    public void saveTrademark(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    @Override
    public BaseTrademark getTrademark(Long trademarkId) {
        return baseTrademarkMapper.selectById(trademarkId);
    }

    @Override
    public void updateTrademark(BaseTrademark baseTrademark) {
        baseTrademarkMapper.updateById(baseTrademark);
    }

    @Override
    public IPage<SpuInfo> getSpuInfoList(Integer page, Integer limit, Long category3Id) {
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id", category3Id);
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page, limit), spuInfoQueryWrapper);


    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //向spu_Info表中添加数据回填主键id
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();

        //向spu_image表中添加信息
        spuImageList.forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });

        //向spu_sale_attr表中添加信息
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);

            //销售属性对应的销售属性值集合
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {

                //填充商品id
                spuSaleAttrValue.setSpuId(spuInfo.getId());

                //填充sale_attr_name
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });

        });


    }

    @Override

    public List<SpuImage> getSpuImageList(Long spuId) {

        QueryWrapper<SpuImage> spuImageQueryWrapper = new QueryWrapper<>();

        spuImageQueryWrapper.eq("spu_id", spuId);

        return spuImageMapper.selectList(spuImageQueryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.SelectSpuSaleAttrList(spuId);

    }

    @Transactional
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //存入sku_info表
        skuInfoMapper.insert(skuInfo);
        //sku对应的图片列表
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            //sku_image表添加信息
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //sku对应的平台属性值列表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            //sku_attr_value表中添加信息
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }

        //sku对应的销售属性值列表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }

    }

    @Override
    public IPage<SkuInfo> list(Integer page, Integer limit) {

        return skuInfoMapper.selectPage(new Page<SkuInfo>(page, limit), null);
    }

    @Override
    public void onSale(Long skuId) {
        skuInfoMapper.onSale(skuId);
        // 向搜索微服务发送消息 更新索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS, MqConst.ROUTING_GOODS_UPPER, skuId);
    }

    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALe);
        skuInfoMapper.updateById(skuInfo);
        // 向搜索微服务发生消息 删除索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS, MqConst.ROUTING_GOODS_LOWER, skuId);
    }

    //查询sku基本信息和sku图片信息列表
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //先查询redis
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (skuInfo == null) {
            //缓存击穿问题
            //加锁
            String cacheLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            String uuid = UUID.randomUUID().toString();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(cacheLock, uuid, 3, TimeUnit.SECONDS);
            if (flag) {
                //获取到锁
                try {
                    //向数据库中查询数据
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (skuInfo != null) {
                        QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
                        skuImageQueryWrapper.eq("sku_id", skuId);
                        List<SkuImage> skuImages = skuImageMapper.selectList(skuImageQueryWrapper);
                        skuInfo.setSkuImageList(skuImages);
                        //缓存雪崩
                        //数据存入redis中,过期时间添加一个随机数，减少同一时刻key集体过期的事件,造成DB数据库在某一时刻压力大，挂掉
                        // 防止缓存雪崩
                        redisTemplate.opsForValue().set(cacheKey, skuInfo, RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    } else {
                        //缓存穿透
                        //存入redis中一个空结果，过期时间是五分钟，缓解缓存穿透，减小DB数据库压力
                        skuInfo = new SkuInfo();
                        redisTemplate.opsForValue().set(cacheKey, skuInfo, 5, TimeUnit.MINUTES);
                    }
                } finally {
                    //解锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLock), uuid);
                }

            } else {
                //未获取到锁
                try {
                    TimeUnit.SECONDS.sleep(3);
                    //向缓存中拿去数据返回
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }
        //redis有值,直接返回
        return skuInfo;
    }

    //查询sku价格信息  需要单独查询 实时更新 不能放入redis缓存中
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null) {
            return skuInfo.getPrice();
        }
        return null;
    }

    //2.获取分类信息
    @Override
    public BaseCategoryView getCategory(Long category3Id) {
        //查询缓存
        String cacheKey = "category" + category3Id + RedisConst.SKUKEY_SUFFIX;
        BaseCategoryView baseCategoryView = (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
        if (baseCategoryView == null) {
            //缓存击穿问题
            //加锁解决
            String cacheLock = "category" + category3Id + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLock);
            try {
                boolean isLock = lock.tryLock(2, 3, TimeUnit.SECONDS);
                if (isLock) {
                    try {
                        //获取到锁
                        //向DB数据库查询数据
                        baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
                        if (baseCategoryView != null) {
                            //数据库中有数据,缓存中保存一份数据，并返回
                            //缓存雪崩问题:过期时间加个随机数
                            redisTemplate.opsForValue().set(cacheKey, baseCategoryView,
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                        } else {
                            //数据库中无此数据
                            //缓存穿透问题:返回空结果,并向缓存中存入空结果
                            baseCategoryView = new BaseCategoryView();
                            redisTemplate.opsForValue().set(cacheKey, baseCategoryView, 5, TimeUnit.MINUTES);
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                } else {
                    //未获取到锁
                    TimeUnit.SECONDS.sleep(3);
                    //再次去缓存中获取数据
                    baseCategoryView = (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return baseCategoryView;
    }

    //3.查询销售属性及属性值集合(选中)
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        //查询redis缓存
        String cacheKey = "getSpuSaleAttrListCheckBySku" + "[" + spuId + "," + skuId + "]" + RedisConst.SKUKEY_SUFFIX;
        List<SpuSaleAttr> spuSaleAttrList = (List<SpuSaleAttr>) redisTemplate.opsForValue().get(cacheKey);
        if (CollectionUtils.isEmpty(spuSaleAttrList)) {
            //缓存三大问题之缓存击穿问题
            //解决方案:加锁
            String cacheLock = "getSpuSaleAttrListCheckBySku" + "[" + spuId + "," + skuId + "]" + RedisConst.SKULOCK_SUFFIX;
            String uuid = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLock, uuid, 3, TimeUnit.SECONDS);
            if (isLock) {
                //获取到锁
                try {
                    //查询DB获取数据
                    spuSaleAttrList = spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(spuId, skuId);
                    if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
                        //缓存三大问题之缓存雪崩问题
                        //解决方案:过期时间加一个随机数
                        //保存数据到缓存中
                        redisTemplate.opsForValue().set(cacheKey, spuSaleAttrList, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                    } else {
                        //DB中也没有数据
                        //缓存三大问题之一:缓存穿透问题
                        //解决方案:向缓存中存入空结果
                        spuSaleAttrList = new ArrayList<>();
                        redisTemplate.opsForValue().set(cacheKey, spuSaleAttrList, 5, TimeUnit.MINUTES);
                    }
                } finally {
                    //解锁
                   /* //无法保证原子性
                    if (redisTemplate.opsForValue().get(cacheLock)==uuid){
                        redisTemplate.delete(cacheLock);
                    }*/
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLock), uuid);
                }

            } else {
                //未获取到锁
                try {
                    TimeUnit.SECONDS.sleep(3);
                    //向缓存中取数据
                    spuSaleAttrList = (List<SpuSaleAttr>) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return spuSaleAttrList;
    }

    @GmallCache(prefix = "getSkuValueIdsMap")
    //4.点击其他销售属性值的组合，跳转到另外的sku页面
    @Override
    public Map getSkuValueIdsMap(Long spuId) {
        List<Map> skuValueIds = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map map = new HashMap();
        if (skuValueIds != null && skuValueIds.size() > 0) {
            skuValueIds.forEach(skuValueId -> {
                map.put(skuValueId.get("value_ids"), skuValueId.get("sku_id"));
            });
        }
        return map;
    }

    //查询所有的一二三级分类信息
    @Override
    public List<BaseCategoryView> getBaseCategoryView() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);

    }

    //查询平台属性集合信息
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }
}
